#!/usr/bin/env python

import os
import time
import lib.component
import sqlalchemy
import sqlalchemy.engine.url

from progressbar import (Bar, ETA, ProgressBar, ReverseBar)


class Console(lib.component.Console):
    """
    Base class for Konata application.
    """

    @staticmethod
    def init_folder():
        """
        Create image and temp folder.

        @return: None
        """

        for folder in ('image', 'temp'):
            if not os.path.lexists(folder):
                os.mkdir(folder)

    def greet(self, resource):
        """
        Print application information.

        Resource must have the following attributes:
            - fullname
            - description
            - version.human
            - date

        @type resource: app
        @param resource: String resource.
        @return: None
        """

        self.warn('%s\n' % resource.fullname)
        self.warn('%s\n' % resource.description)
        self.warn('Version %s\n' % resource.version.human)
        date = resource.date.strftime("%A, %B %d, %Y")
        self.warn('Released at %s\n\n' % date)

    def farewell(self):
        """
        Print application shut down message.

        @return: None
        """

        self.warn('\nGood bye ^_^\n')

    def open_db(self, echo=False):
        """
        Open database session

        @type echo: bool
        @param echo:A boolean whether to echo the sql command or not. Useful for
            debugging.

        @rtype: ScopedSession
        @return: SqlAlchemy session object.
        """

        import model

        database = 'Lucky Star.db'
        driver = 'sqlite'
        url = sqlalchemy.engine.url.URL(driver, database=database)
        engine = sqlalchemy.create_engine(url, echo=echo)
        model.init(engine)
        session = model.DbSession()
        model.metadata.create_all(engine)
        self.import_host(session)
        self.import_search(session)
        return session

    @staticmethod
    def sleep(value):
        """
        Sleep and show progress bar.

        @type value: int
        @param value: Time in second.

        @rtype: bool
        @return: Boolean indicating detected keyboard interrupt. Returns True if
            Ctrl+C detected.
        """

        maximum = value * 100
        widgets = [Bar('>'), ' ', ETA(), ' ', ReverseBar('<')]
        gauge = ProgressBar(widgets=widgets, maxval=maximum).start()
        aborted = False

        for i in range(maximum):
            try:
                gauge.update(i)
                time.sleep(.01)
            except KeyboardInterrupt:
                aborted = True
                break
        if not aborted:
            gauge.finish()
        else:
            print ''

        return aborted

    def import_host(self, session):
        """
        Import host data from data/host.csv if hosts table is empty.

        Csv first row must reflect field name in table.

        @type session: ScopedSession
        @param session: SqlAlchemy scoped session object.
        @return: None
        """

        import csv
        import model

        result = session.query(model.Host).first()
        if result:
            return

        self.progress('Importing host data... ')

        filename = os.path.join('data', 'host.csv')
        with open(filename, 'r') as csv_file:
            rows = csv.reader(csv_file, delimiter=',', quotechar='"')
            is_virgin = True
            for data in rows:
                if is_virgin:
                    headers = data
                    is_virgin = False
                    continue

                host = model.Host()
                for index, _ in enumerate(headers):
                    setattr(host, headers[index], data[index])
                session.add(host)
                session.commit()

        self.cheer('OK ^_^\n')

    def import_search(self, session):
        """
        Import search data from data/search.txt if searches table is empty.

        Each row in csv file will become one row in table.

        @param session: ScopedSession
        @return: None
        """

        import os
        import model

        result = session.query(model.Search).first()
        if result:
            return

        self.progress('Importing search tag... ')

        for search_value in ['artist', 'misc']:
            path = os.path.join('data', 'search', '%s.txt' % search_value)
            file_object = open(path, 'r')
            for line in file_object:
                search = model.Search(value=line.strip())
                session.add(search)
            file_object.close()
            session.commit()

        self.cheer('OK ^_^\n')
